package com.eshop.eshopcache.listener;

import com.eshop.eshopcache.rebuild.RebuildCacheQueue;
import com.eshop.eshopcache.rebuild.RebuildCacheThread;
import com.eshop.eshopcache.spring.SpringContext;
import com.eshop.eshopcache.zk.ZooKeeperSession;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author: Xukai
 * @description: 初始化监听对象（具体业务类）
 * @createDate: 2018/7/23 00:48
 * @modified By:
 */
@Slf4j
public class InitListener implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        // 获取spring上下文
        ServletContext servletContext = sce.getServletContext();
        WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(servletContext);
        SpringContext.setApplicationContext(context);
        // 初始化zk连接
        ZooKeeperSession.init();
        // 初始化重建队列
        RebuildCacheQueue.init();
        ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("RebuildCacheThread").build();
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                1,
                1,
                0L,
                TimeUnit.MILLISECONDS,
                new LinkedBlockingDeque<>(),
                namedThreadFactory,
                new ThreadPoolExecutor.AbortPolicy());
        threadPoolExecutor.submit(new RebuildCacheThread());
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {

    }
}
